package com.springboot.file.fastdfs;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.springboot.file.FileException;
import com.springboot.file.filebase.IFileStorageInterface;
import com.springboot.file.filedto.MultipartFileDto;
import org.apache.commons.io.FilenameUtils;
import org.csource.common.MyException;
import org.csource.fastdfs.ProtoCommon;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import jakarta.annotation.Resource;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

/**
 * @Classname FastdfsStorageService
 * @Description TODO
 * @Version 1.0.0
 * @Date 2024/1/11 16:40
 * @Created by zyj
 */
@Component
public class FastDfsStorageService implements IFileStorageInterface {

    @Resource
    private FastFileStorageClient storageClient;
    @Value("${fdfs.http.http_secret_key:123456}")
    private String securityKey;

    @Value("${fdfs.http.myFileUrl:123456}")
    private String myFileUrl;

    @Override
    public String uploadMultipartFile(MultipartFileDto multipartFileDto) throws FileException {
        MultipartFile multipartFile = multipartFileDto.getMultipartFile();
        String path = null;
        try {
            String type = FilenameUtils.getExtension(multipartFile.getOriginalFilename());
            //文件上传：参数一：传输文件内容的输入流；
            // 参数二：文件的size；参数三：文件扩展名；参数四：描述文件的元数据；返回值：上传文件在存储节点的唯一标识（卷名+文件名）
            StorePath storePath = storageClient.uploadFile(multipartFile.getInputStream(), multipartFile.getSize(), type, null);
            path = storePath.getFullPath();
        } catch (IOException e) {
            throw new FileException("fastdfs文件上传失败：", e);
        }
        return path;
    }

    @Override
    public byte[] downloadFile(String filePath) throws FileException{
        String group = filePath.substring(0, filePath.indexOf("/"));
        String path = filePath.substring(filePath.indexOf("/") + 1);
        DownloadByteArray downloadByteArray = new DownloadByteArray();
        byte[] bytes = storageClient.downloadFile(group, path, downloadByteArray);
        return bytes;
    }

    @Override
    public boolean deleteFile(String filePath) throws FileException {
        storageClient.deleteFile(filePath);
        return true;
    }

    @Override
    public String getFileLink(String filePath) throws FileException {

        try {
            return myFileUrl +"/"+getTokenFastDfs(filePath);
        } catch (Exception e) {
            throw new FileException("fastDf获取文件失败",e);
        }
    }

    @Override
    public String getDomain() {
        return myFileUrl;
    }


    /***
     * @Description: fastdfs 添加token
     * @Param: [path]
     * @return: java.lang.String
     * @Author: zyj
     * @Date: 2020/11/25
     */
    public String getTokenFastDfs(String path) throws Exception{

        // 获取当前时间戳
        int ts = (int)(System.currentTimeMillis()/1000);

        // 获取Token, 传入的文件ID不要含有分组信息
        //组名
        String group = path.split("/")[0];
        //文件名
        String filePath = path.substring(group.length()+1, path.length());
        String token =  ProtoCommon.getToken(filePath, ts, securityKey);
        return path+"?token=" + token + "&ts=" + ts;
    }


}
